package com.gonfre.quientelo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.getbase.floatingactionbutton.FloatingActionButton;

import util.DataBaseManager;
import util.MyDBObject;
import util.MyDataBase;
import util.Response;


public class MultiSelectorActivity extends MyActivity {
    LinearLayout layoutRoot;
    RelativeLayout layoutRootPpal;
    public MyDBObject[] items = null;
    public String selectedItems = "";
    public String selectedItemsName = "";
    public boolean multiSelector = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        ScrollView scrollView = new ScrollView(this);
        LayoutParams layoutParamsScroll = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        scrollView.setLayoutParams(layoutParamsScroll);


        layoutRootPpal = new RelativeLayout(this);
        LayoutParams layoutParamsPpal = new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutRootPpal.setLayoutParams(layoutParamsPpal);


        layoutRoot = new LinearLayout(this);
        layoutRoot.setOrientation(LinearLayout.VERTICAL);

        // Configuring the width and height of the linear layout.
        LayoutParams layoutParamsRoot = new LayoutParams(
                //android:layout_width="match_parent" an in xml
                LinearLayout.LayoutParams.MATCH_PARENT,
                //android:layout_height="wrap_content"
                LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParamsRoot.setMargins(0, 50, 0, 50);
        layoutRoot.setLayoutParams(layoutParamsRoot);

        DataBaseManager dbm = new DataBaseManager(this);
        String table = this.getString(R.string.table_categoria);
        String sql_table = this.getString(R.string.sql_categoria);
        String query_item_categoria = this.getString(R.string.query_item_categoria);
        MyDataBase dbCategories = new util.MyDataBase(this, dbm, table, sql_table);

        items = dbCategories.readItemCategory(query_item_categoria, "", "nombre", "id", "icono");

        // Obtengo los items ya seleccionados
        Bundle bundle = getIntent().getExtras();
        multiSelector = bundle.getBoolean("multiSelector");
        selectedItems = bundle.getString("selectedItems");
        selectedItemsName = bundle.getString("selectedItemsName");
        String selectedItemsTemp = "," + selectedItems + ",";
        Log.i("Trace MultiSelectorActivity 'OnCreate' selectedItems", selectedItems);
        for(int i=0; i < items.length; ++i){
            if(selectedItemsTemp.indexOf(","+items[i].objectId+",") >= 0){
                items[i].objectSelected = true;
            }
            addLayoutChild(i, items[i].objectName, items[i].objectIcon, items[i].objectSelected);
        }
        addLayoutChildEmpty();
        scrollView.addView(layoutRoot);

        // Seteo Layout padre
        layoutRootPpal.addView(scrollView);
        addButtonFinish();

        setContentView(layoutRootPpal);
    }

    private void addLayoutChild(final int itemId, String name, String icon, boolean sel){
        // Creo el Layout Hijo
        RelativeLayout layoutChild = new RelativeLayout(this);
        RelativeLayout.LayoutParams layoutParamsChild = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutChild.setPadding(5,5,5,5);
        layoutChild.setLayoutParams(layoutParamsChild);

        // Agrega Icono a Layout Hijo
        ImageView itemIcon = new ImageView(this);
        //Log.i("Trace MultiSelectorActivity 'addLayoutChild' icon", icon);
        byte[] decodedString = Base64.decode(icon, Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        itemIcon.setImageBitmap(decodedByte);
        //itemIcon.setTop(10);
        //setLayoutParams(itemIcon, RelativeLayout.ALIGN_PARENT_LEFT, 0,8,0,0);
        setLayoutParams(itemIcon, RelativeLayout.CENTER_VERTICAL);
        layoutChild.addView(itemIcon);

        // Agrega Texto a Layout Hijo
        TextView itemName = new TextView(this);
        itemName.setText(name);
        setLayoutParams(itemName, RelativeLayout.ALIGN_PARENT_LEFT, 30, 0, 0, 0);

        itemName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox ch = (CheckBox)findViewById(itemId);
                if(multiSelector) {
                    if(ch.isChecked()) {
                        ch.setChecked(false);
                        items[ch.getId()].objectSelected = false;
                    }else {
                        ch.setChecked(true);
                        items[ch.getId()].objectSelected = true;
                    }
                }else{
                    if (ch.isChecked()) {
                        Log.i("Trace MultiSelectorActivity 'OnClickListener' isChecked", "" + items[ch.getId()].objectId);
                        // No se hace nada
                    } else {
                        Log.i("Trace MultiSelectorActivity 'OnClickListener' isNotChecked", "" + items[ch.getId()].objectId);
                        cleanSelectedItems(ch.getId());
                        ch.setChecked(true);
                        items[ch.getId()].objectSelected = true;
                    }
                }

                setSelectedItems();
            }
        });
        layoutChild.addView(itemName);
        layoutChild.setBackground(getResources().getDrawable(R.drawable.checklist_item));

        // Agrega Check a Layout Hijo
        CheckBox itemCheck = new CheckBox(this);
        if(sel)
            itemCheck.setChecked(true);
        else
            itemCheck.setChecked(false);
        itemCheck.setId(itemId);

        itemCheck.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox ch = (CheckBox) v;
                if(multiSelector) {
                    if (ch.isChecked()){
                        Log.i("Trace MultiSelectorActivity 'OnClickListener' ObjectId", ""+items[ch.getId()].objectId);
                        items[ch.getId()].objectSelected = true;
                    }else{
                        items[ch.getId()].objectSelected = false;
                    }
                }else {
                    if (ch.isChecked()) {
                        Log.i("Trace MultiSelectorActivity 'OnClickListener' isChecked", "" + items[ch.getId()].objectId);
                        cleanSelectedItems(ch.getId());
                        items[ch.getId()].objectSelected = true;
                    } else {
                        Log.i("Trace MultiSelectorActivity 'OnClickListener' isNotChecked", "" + items[ch.getId()].objectId);
                        cleanSelectedItems(ch.getId());
                        ch.setChecked(true);
                        items[ch.getId()].objectSelected = true;
                    }
                }
                setSelectedItems();
            }
        });
        setLayoutParams(itemCheck, RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutChild.addView(itemCheck);

        // Agrega Layout hijo a Layout Padre
        layoutRoot.addView(layoutChild);
    }

    private void addLayoutChildEmpty() {
        // Creo el Layout Hijo
        RelativeLayout layoutChild = new RelativeLayout(this);
        RelativeLayout.LayoutParams layoutParamsChild = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutChild.setPadding(0, 90, 0, 90);
        layoutChild.setLayoutParams(layoutParamsChild);
        layoutRoot.addView(layoutChild);
    }

    private void addButtonFinish(){
        com.getbase.floatingactionbutton.FloatingActionButton b = new com.getbase.floatingactionbutton.FloatingActionButton(this);
        b.setSize(FloatingActionButton.SIZE_MINI);
        b.setIconDrawable(getResources().getDrawable(R.drawable.ic_done_white_24dp));
        b.setColorNormal(getResources().getColor(R.color.buttonColor));
        b.setColorPressed(getResources().getColor(R.color.buttonColorPressed));

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_END);
        //params.setMargins(0, 0, 16, 16);
        b.setLayoutParams(params);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishWithResult();
            }
        });

        layoutRootPpal.addView(b);
    }

    private void setLayoutParams(View v, int centerInParent, int marginLeft, int marginTop, int marginRight, int marginBottom) {
        // Defining the layout parameters of the Button
        RelativeLayout.LayoutParams layoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        // Add Margin to the LayoutParameters
        layoutParameters.setMargins(marginLeft, marginTop, marginRight, marginBottom);

        // Add Rule to Layout
        layoutParameters.addRule(centerInParent);

        // Setting the parameters on the Button
        v.setLayoutParams(layoutParameters);
    }

    private void setLayoutParams(View v, int centerInParent) {
        // Just call the other AddButtonLayout Method with Margin 0
        setLayoutParams(v, centerInParent, 0, 0, 0, 0);
    }

    public void setSelectedItems(){
        String it = "", itname = "";
        int j = 0;
        for(int i=0; i < items.length; ++i){
            if (items[i].objectSelected) {
                j++;
                if(j == 1) {
                    it = items[i].objectId;
                    itname = items[i].objectName;
                }else {
                    it = it + "," + items[i].objectId;
                    itname = itname + "," + items[i].objectName;
                }
            }
        }
        selectedItems = it;
        selectedItemsName = itname;
    }

    public void cleanSelectedItems(int idExp){
        CheckBox ch;
        for(int i=0; i < items.length; ++i){
            if(idExp != i) {
                items[i].objectSelected = false;
                ch = (CheckBox) findViewById(i);
                ch.setChecked(false);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_multi_selector, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFinishRequest(int type, Response res) {

    }

    private void finishWithResult()
    {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("selectedItems", selectedItems);
        returnIntent.putExtra("selectedItemsName", selectedItemsName);
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    @Override
    public void onBackPressed() {
        finishWithResult();
    }
}
